package cn.lml.lession.auth.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import cn.lml.lession.auth.service.ModuleService;
import cn.lml.lession.auth.service.RoleService;
import cn.lml.lession.auth.service.UserService;
import cn.lml.lession.common.vo.ModuleVo;
import cn.lml.lession.common.vo.RoleVo;
import cn.lml.lession.common.vo.UserVo;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ModuleService moduleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	UserVo userVo = userService.findUserByUsername(username);
        if (userVo == null) {
            throw new UsernameNotFoundException("用户:" + username + ",不存在!");
        }
    	List<RoleVo> roleList=roleService.queryRoleByUserId(userVo.getUid());
    	Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        boolean enabled = true; // 可用性 :true:可用 false:不可用
        boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
        boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
        boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定
             for (RoleVo role:roleList){
                 //角色必须是ROLE_开头，可以在数据库中设置
                 GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+role.getRname());
                 grantedAuthorities.add(grantedAuthority);
                 //获取权限
                 List<ModuleVo> moduleList = moduleService.queryModuleByRoleId(role.getRid());
                     for (ModuleVo menu:moduleList) {
                         GrantedAuthority authority = new SimpleGrantedAuthority(menu.getMname());
                         grantedAuthorities.add(authority);
                     }
                 }
         User user = new User(userVo.getUsername(), userVo.getPassword(),
                 enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
         return user;
    }
}
